from flask import request, jsonify
from flask_restful import Resource
from pymongo import MongoClient
from config.config import (WX, db)
from wechatpy import WeChatClient
from wechatpy.client.api import WeChatMessage
from wechatpy.client.api.media import WeChatMedia
from service import redis_service

class Service(Resource):
    def __init__(self, rest_type=None):
        self.type = rest_type
        self.client = WeChatClient(WX.get("appid"), WX.get("appsecret"))
        self.message = WeChatMessage(self.client)
        self.media = WeChatMedia(self.client)
        self.host = db.get("host")
        self.port = db.get("port")
        self.db_client = MongoClient(self.host, self.port)
        self.db = self.db_client.tao  # Select the database
        self.devices = self.db.devices  # Select th

    def get_template_id_by_name(self, template_name):
        template_list_dict = self.client.template.get_all_private_template()
        if len(template_list_dict.get("template_list")) > 0:
            for temp_template in template_list_dict.get("template_list"):
                if temp_template["title"] == template_name:
                    return temp_template["template_id"]
        return None

    def get(self):
        return {'hello': 'world'}

    def post(self):
        json_data = request.get_json(force=True)
        msg_type = None
        msg_content = None
        msg_open_id = None
        msg_sn = None
        device_name = "设备"

        if 'type' in json_data:
            msg_type = json_data['type']
        else:
            return jsonify(errorCode=1, errorMsg='No type.')
        if 'sn' in json_data:
            msg_sn = json_data['sn']
        else:
            return jsonify(errorCode=4, errorMsg='No SN.')
        if 'openid' in json_data:
            msg_open_id = json_data['openid']
            devices_obj = self.devices.find_one({"openid": msg_open_id, "sn": msg_sn})
            if devices_obj is not None and "name" in devices_obj:
                device_name = devices_obj.get("name")
        else:
            return jsonify(errorCode=3, errorMsg='No openid.')
        if 'content' in json_data:
            msg_content = {"type": "0", "content": json_data['content'], "sender": json_data['sn'], "to": "msg_open_id",
                           "name": device_name}
        else:
            return jsonify(errorCode=2, errorMsg='No content.')
        socket_name = redis_service.session.get("room")
        if socket_name is not None and socketIo.server.manager.rooms["/chat"].get(socket_name) is not None:
            if "0" == msg_type:
                msg_content["type"] = "0"
            elif "1" == msg_type:
                msg_content["type"] = "1"
                # self.message.send_text(msg_open_id, msg_content)
            elif "2" == msg_type:
                msg_content["type"] = "2"
                # self.message.send_image(msg_open_id, msg_content)
            elif "3" == msg_type:
                msg_content["type"] = "3"
                # self.message.send_text(msg_open_id, msg_content)
            elif "6" == msg_type:
                msg_content["type"] = "6"
                # self.message.send_text(msg_open_id, msg_content)
            elif "7" == msg_type:
                msg_content["type"] = "7"
                # self.message.send_text(msg_open_id, msg_content)

            try:
                res = socketIo.emit('device_message', msg_content, namespace='/chat', room=socket_name)
                print(res)
            except Exception as e:
                print(str(e))
                return jsonify(errorCode=1, errorMsg='NOK')
        else:
            text_template_id = self.get_template_id_by_name("消息推送测试")
            template_msg_content = {"first": {"value": "消息测试"},
                                    "keyword1": {"value": "\n{}的消息内容：{}".format(device_name, json_data["content"]),
                                                 "color": "blue"}}
            redis_service.session.set("url_redirect", "/record?sn={}".format(msg_sn))
            res = self.message.send_template(user_id=msg_open_id,
                                             template_id=text_template_id, data=template_msg_content,
                                             url="https://open.weixin.qq.com/connect/oauth2/authorize?appid"
                                                 "=wxe566d7c50a4d2cf9&redirect_uri=http%3A%2F%2Feaa92b9c.ngrok.io"
                                                 "%2Fauth&response_type=code&scope=snsapi_base&state=STATE")
            if "errmsg" in res and res.get("errmsg") != "ok":
                return jsonify(errorCode=1, errorMsg='NOK')
        return jsonify(errorCode=0, errorMsg='OK')
